package com.tianqingwl.gsystem.install.service.impl;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.tianqingwl.gsystem.common.util.SpringUtil;
import com.tianqingwl.gsystem.install.mapper.InstallMapper;
import com.tianqingwl.gsystem.install.service.InstallService;
import com.tianqingwl.gsystem.install.vo.InstallInfoVo;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;

@Service
public class InstallServiceImpl implements InstallService {

    @Autowired
    private InstallMapper installMapper;
    @Autowired
    private DataSourceProperties properties;
    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public void initSiteData(InstallInfoVo installInfoVo){
        //获取数据库信息
        String dbHost = installInfoVo.getDbHost();
        String dbName = installInfoVo.getDbName();
        String dbPort = installInfoVo.getDbPort();
        String dbUser = installInfoVo.getDbUser();
        String dbPassword = installInfoVo.getDbPassword();
        String url = "jdbc:mysql://"+dbHost+":"+dbPort+"/"+dbName+"?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&allowMultiQueries=true";
        //切换到指定数据源
        Configuration configuration = ((DefaultSqlSessionFactory) SpringUtil.getBean("sqlSessionFactory"))
                .getConfiguration();
        try {
            //重置数据源
            properties.setUrl(url);
            properties.setUsername(dbUser);
            properties.setPassword(dbPassword);
            DataSource dataSource = properties.initializeDataSourceBuilder().build();
            Connection connection = dataSource.getConnection();
            if (connection==null){
                throw new RuntimeException("无法连接数据库，请检查数据库配置信息");
            }
            configuration.setEnvironment(new Environment(MybatisSqlSessionFactoryBean.class.getSimpleName(),
                    new SpringManagedTransactionFactory() ,
                    dataSource));
        } catch (Exception throwables) {
            throw new RuntimeException("无法连接数据库，请检查数据库配置信息");
        }
        installMapper.createTable();
        installMapper.updateDefaultSite(installInfoVo.getSiteName(),installInfoVo.getDomain());
        String encode = passwordEncoder.encode(installInfoVo.getManagePassword());
        installMapper.updateDefaultManager(installInfoVo.getManageUsername()
                ,installInfoVo.getManageShowName()
                , encode);
    }



}
